<script setup>
/**
 * & 文件引入区域
 */
import {
  ref,
  onUnmounted,
  onActivated,
  onBeforeMount,
  onDeactivated,
  onMounted,
  watch,
  nextTick
} from "vue";
import { useRouter, useRoute } from "vue-router";

import {
  topCateList,
  selectBgImgList,
  itemSearchCommodity,
} from "@/server/api/itemApi";

import { itemStore } from "@/stores/item";
import { useUseStore } from "@/stores/user";

import { splitArray } from "@/hook/dataProcessing";
import { useIndexStore } from "@/stores/indexStore";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
/**
 * & 变量声明区
 */

const route = useRoute();
const router = useRouter();
const useStore = useIndexStore();

// 状态管理
let isLoading = ref(false); // 是否正在加载
let hasMoreData = ref(true); // 是否还有更多数据
let isRerequire = ref(true); // 是否允许加载更多


let products = ref(); // 获取title的Dom元素
let top_boxShadow = ref(false); // 控制title样式
let swiperData = ref(); // 轮播图数据
// 商品数据接口请求体
let CommodityReq = ref({
  commodityId: null,
  commodityName: "",
  freeShippingNum: 0,
  priceOrder: 0, //价格排序条件 0:降序 1:升序
  degreeLoss: 0,
  start: 1,
  size: 10,
  countryCode: [useUseStore().countryCode]
})

// 筛选框Items
let selectItemObj = ref([
  {
    title: "item.screen.price",
    items: [
      {
        title: "item.screen.ascending",
        bid: 0,
      },
      {
        title: "item.screen.descending",
        bid: 1,
      },
    ],
  },
  //
  // { 
  //   title: "item.screen.freight",
  //   items: [
  //     {
  //       title: "item.screen.free_shipping",
  //       bid: 0,
  //     },
  //   ],
  // },
]);
let baseUrl = useUseStore().ing; //图片拼接基本路径
let isScreen = ref(false); // 用于判断用于是否有筛选，有则为true，卸载组件是删除store数据，使得下次重新请求
useStore.isShow = 1;


const showPopover = ref(false);
const productList = ref([]);//商品数据

/**
 * & 函数区
 */
// 跳转到分类页面


const getPlacement = (item) => {
  const element = document.querySelector(
    `[data-category-id="${item.categoryId}"]`
  );
  if (!element) return "bottom";

  const rect = element.getBoundingClientRect();
  const windowWidth = window.innerWidth;

  // 动态判断边距
  if (rect.left < 100) return "right";
  if (windowWidth - rect.right < 100) return "left";
  return "bottom";
}


const toCategoryFun = (categoryId) => {

  showPopover.value = false; // 先关闭气泡
  setTimeout(() => {
    router.push({
      path: "/category",
      query: {
        categoryId,
      },
    });
  }, 300); // 延时 300 毫秒，与气泡的关闭动画时长匹配

};

// 滚动监听title是否贴顶, 监听用户滑动到底部加载商品数据
const scrollFun = () => {
  const productsDom = document.getElementById("products");
  if (!productsDom || !hasMoreData.value || isLoading.value) return;

  const homePage = document.querySelector('.homePage');
  const scrollTop = homePage.scrollTop;
  const offsetHeight = homePage.offsetHeight;
  const scrollHeight = homePage.scrollHeight;

  const remainingScroll = scrollHeight - (scrollTop + offsetHeight);

  if (remainingScroll < 800 && isRerequire.value) {
    isRerequire.value = false; // 防止重复请求
    itemSearchCommodityFun('loadMore').then(() => {
      isRerequire.value = true; // 恢复请求权限
    });
  }
};

// 根据跳转ProductsDetail页面
const goProductsDetail = (id) => {
  router.push({
    path: "/details",
    query: {
      id,
    },
  });
};

// 获取轮播图数据
const selectBgImgListFun = async () => {
  let res = await selectBgImgList(0);
  res.data.data.forEach((item) => (item.imgUrl = baseUrl + item.imgUrl));

  swiperData.value = res.data.data;
};

// 获取首页分类标签接口
const getCategoryList = async () => {
  let res = await topCateList(0);
  res.data.data.forEach((item) => (item.imgUrl = baseUrl + item.originPath));

  itemStore().cateData = splitArray(res.data.data, 8);
};


// 商品列表数据接口
const itemSearchCommodityFun = async (type = 'default') => {
  // if (isLoading.value) return; // 防止重复请求

  isLoading.value = true; // 开始加载

  // 如果是刷新或切换地区，重置分页和商品列表
  if (type === 'refresh' || type === 'regionChange') {
    CommodityReq.value.commodityName = "";
    CommodityReq.value.start = 1; // 重置页码
    productList.value = []; // 清空列表
    hasMoreData.value = true; // 重置更多数据状态
  }
  if (type === 'search') {
    CommodityReq.value.start = 1; // 重置页码
    productList.value = []; // 清空列表
    hasMoreData.value = true; // 重置更多数据状态
  }
  try {
    const res = await itemSearchCommodity(CommodityReq.value);

    if (res?.data?.code === 200) {
      const list = res?.data?.data?.list || [];

      if (CommodityReq.value.start === 1) {
        productList.value = list; // 如果是第一页，覆盖数据
      } else {
        productList.value.push(...list); // 否则追加数据
      }

      if (list.length < CommodityReq.value.size) {
        hasMoreData.value = false; // 没有更多数据了
      } else {
        CommodityReq.value.start += 1; // 页码自增
      }
    } else {
      console.error("请求失败或数据异常");
    }
  } catch (error) {
    console.error("请求失败", error);
  } finally {
    isLoading.value = false; // 结束加载
  }
};


// 模糊搜索方法
const searchFun = (vl) => {
  // 赋值请求体
  CommodityReq.value.commodityName = vl;
  CommodityReq.value.start = 1; // 重回第一页
  // 使得用户下次进入页面重新请求数据
  isScreen.value = true;
  itemSearchCommodityFun('search'); // 触发搜索逻辑
};

// 处理获取到的数据接口
const ProcessingFun = (isItemShowId, id) => {

  // 使得用户下次进入页面重新请求数据
  isScreen.value = true;

  if (isItemShowId === 0) {
    CommodityReq.value = {
      commodityId: null,
      commodityName: "",
      freeShippingNum: 0,
      priceOrder: id,
      degreeLoss: 0,
      start: 1,
      size: 4,
      countryCode: [useUseStore().countryCode]
    };
  } else if (isItemShowId === 1) {
    CommodityReq.value = {
      commodityId: null,
      commodityName: "",
      freeShippingNum: id,
      priceOrder: 0,
      degreeLoss: 0,
      start: 1,
      size: 4,
      countryCode: [useUseStore().countryCode]
    };
  }
  itemSearchCommodityFun('search');
};

// 切换地区修改数据方法
const addressChangeItemDataFun = (id) => {

  CommodityReq.value.countryCode = id;
  itemSearchCommodityFun('regionChange'); // 触发地区切换逻辑
};

/**
 * 跳转活动页面函数
 */
const toActivity = () => {
  router.push("activity");
};


watch(
  () => route.fullPath, // 监听路径变化
  () => {
    showPopover.value = false; // 路由切换时重置
  }
);


// 在组件挂载前请求api接口
onBeforeMount(() => {
  selectBgImgListFun(); // 轮播图数据
  itemStore().cateData ? "" : getCategoryList(); // 分类标签数据
});

// 组件激活时调用
onActivated(() => {
  itemSearchCommodityFun('default'); // 页面激活时加载数据
});

// 组件卸载生命周期函数
onUnmounted(() => {
  productList.value = [];
  CommodityReq.value.start = 1;
});
</script>

<template>
  <div class="homePage" @scroll="scrollFun" ref="products">
    <!-- 顶部 -->
    <div class="top">
      <TopBar :type="1" @searchFun="searchFun" @itemDataChangeFun="addressChangeItemDataFun" :isScaner="true" />
    </div>

    <!-- 活动入口按钮  二级分销 开团 以后开启不要删除 -->
    <!-- <div class="activity" @click="toActivity">
      <img src="/images/piftware.png" alt="" />
    </div> -->

    <!-- 轮播图 -->
    <!-- <div class="swipe" dir="ltr">
      <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
        <van-swipe-item v-for="item in swiperData" :key="item.contentId">
          <img alt="" v-lazy="item.imgUrl" @click="goProductsDetail(item.contentId)" />
        </van-swipe-item>
      </van-swipe>
    </div> -->

    <!-- 分类 -->
    <div class="classification" dir="ltr">
      <van-swipe v-if="itemStore().cateData">
        <van-swipe-item v-for="(item, index) in itemStore().cateData" :key="index">
          <div class="content">
            <div class="item" v-for="vl in item" :key="vl.categoryId" :data-category-id="vl.categoryId">
              <!-- 控制每个分类独立显示 -->
              <van-popover :show="showPopover" :placement="getPlacement(vl)">
                <template #default>
                  <div class="popover-content" style="background-color: blueviolet; border-radius: 30rem;">
                    <div class="popover-main" @click="toCategoryFun(vl.categoryId)">
                      <div class="popover-title" style="font-size: 30rem; padding: 12rem">
                        {{ $t(`item.categoryTitle.${vl.content}`) }}
                      </div>
                    </div>
                  </div>
                </template>
                <template #reference>
                  <div>
                    <img v-lazy="vl.imgUrl" alt="" />
                    <div class="title">
                      {{ $t(`item.categoryTitle.${vl.content}`) }}
                    </div>
                  </div>
                </template>
              </van-popover>
            </div>
          </div>
        </van-swipe-item>
      </van-swipe>
    </div>

    <!-- 商品列表 -->
    <ProductsList :top_boxShadow="top_boxShadow" :data="productList" v-show="productList && productList.length > 0"
      :title="$t('item.title')" :isScreen="false" ref="products" id="products" :topNum="0">
      <!-- 筛选框 -->
      <template #selectBox>
        <SelectBox :top_boxShadow="top_boxShadow" :moreBtn="true" :data="selectItemObj"
          @ProcessingFun="ProcessingFun" />
      </template>
    </ProductsList>
    <div v-if="!hasMoreData" class="no-more-data">
      {{ $t('item.noMoreData') }}

    </div>
  </div>
</template>

<style lang="scss" scoped>
.homePage {
  min-height: 100vh;
  max-height: 100vh;
  overflow-y: scroll;

  .btn {
    font-size: 12rem;
    padding: 20rem;
  }

  &::-webkit-scrollbar {
    display: none;
  }

  .activity {
    width: 30rem;
    height: 30rem;
    padding: 3rem;
    border-radius: 50%;
    // border: 1rem solid #ccc;
    background: #fff;

    position: absolute;
    z-index: 100;
    top: 15%;
    right: 0;

    >img {
      width: 100%;
      height: 100%;
    }
  }

  .top {
    padding: 0 2rem;
  }

  .swipe {
    padding: 0 16rem;
    margin-bottom: 16rem;

    .my-swipe {
      border-radius: 12rem;

      :deep(.van-swipe__indicators) {
        >.van-swipe__indicator {
          background-color: rgb(87, 87, 87);

          &.van-swipe__indicator--active {
            background-color: rgb(143, 143, 143) !important;
          }
        }
      }

      img {
        width: 100%;
        height: 200rem;
        object-fit: contain;
      }

      :deep(.van-swipe__indicator--active) {
        padding: 0 3rem;
        border-radius: 3rem;
      }
    }
  }

  .classification {
    margin: 0 12rem 4rem 16rem;
    border-radius: 12rem;
    background: #fff;
    box-shadow: 3rem 3rem 10rem 0 #f0f0f0;

    .content {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      padding: 17rem 9rem 32rem;

      .item {
        display: flex;
        flex-direction: column;
        align-items: center;

        min-width: 70rem;
        margin-bottom: 12rem;

        &:nth-of-type(4n) {
          margin-right: 0;
        }

        img {
          margin-bottom: 4rem;
          width: 44rem;
          height: 44rem;
        }

        .title {
          width: 60rem;
          font-size: 14rem;
          text-align: center;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }


        .van-popover {
          --popover-background-color: #4b0b57;
          /* 气泡背景色：柔和的浅粉紫 */
          --popover-border-radius: 12px;
          /* 圆角大小 */
          --popover-text-color: #4a4a4a;
          /* 文字颜色 */
          --popover-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
          /* 阴影增强视觉效果 */
        }

        :deep(.van-popover) {
          max-width: calc(100vw - 20px);
          /* 防止宽度超出视口 */
          overflow: visible;
        }

        .popover-content {
          padding: 10rem;
          text-align: center;
          background-color: blueviolet;
          // border-radius: 30rem;
        }


        .popover-main {
          background-color: #6b0f7d;
          /* 主体背景色 */
          border-radius: 30rem;
          /* 主体圆角 */
          box-shadow: 0 4rem 8rem rgba(0, 0, 0, 0.1);
          /* 添加柔和阴影 */
          padding: 16rem;
          cursor: pointer;
          transition: transform 0.2s, box-shadow 0.2s;
          /* 动态效果 */
        }

        .popover-main:hover {
          transform: scale(1.05);
          /* 鼠标悬停时放大效果 */
          box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
          /* 悬停时阴影增强 */
        }

        .popover-title {
          font-size: 18px;
          /* 文字大小 */
          font-weight: bold;
          /* 加粗 */
          color: #6a1b9a;
          /* 文字颜色：深紫色 */
          margin-top: 8px;
        }

        .title {
          color: #6a1b9a;
          /* 分类标题的颜色 */
        }

        img {
          border-radius: 8px;
          /* 图片圆角 */
          margin-bottom: 8px;
        }

      }

      // @media screen and (max-width: 350rem) {
      //   .item {
      //     margin-right: 8rem;
      //   }
      // }
    }

    :deep(.van-swipe__indicator--active) {
      padding: 0 5rem;
      border-radius: 3rem;
      background: rgba(100, 46, 142, 1);
    }

  }

  .no-more-data {
    margin-top: 16rem;
    font-size: 16rem;
    display: flex;
    justify-content: center;
  }

}
</style>
